package com.pucong.gitee.database.backup.configuration.authorize;


import lombok.extern.slf4j.Slf4j;

import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author lenovo
 * @date 2020/01/03
 */
@Slf4j
public class RSASignature {
    public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    public static final String ENCODE = "UTF-8";

    public static String pubicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDX6KuitMZBeVAER1PzcKBpZ/otlOz4pDMFR1AlUoGUeAZ8QiR92Ttr4gFtrjw7vaEhWgEpjmW0d/aRciMBZXYvB/EUz/GKUSeY+5k0q54diRNoy/8yfGdfdZUKODbZ6sUz8MfwKf64U6Xtb30JbnY/GpSFkem547rYBr00F/knDwIDAQAB";

    public static String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANfoq6K0xkF5UARHU/NwoGln+i2U7PikMwVHUCVSgZR4BnxCJH3ZO2viAW2uPDu9oSFaASmOZbR39pFyIwFldi8H8RTP8YpRJ5j7mTSrnh2JE2jL/zJ8Z191lQo4NtnqxTPwx/Ap/rhTpe1vfQludj8alIWR6bnjutgGvTQX+ScPAgMBAAECgYBB5HdlO6h52O0rsR0U4Z2DLcFzYc0EgRA1HzN9gHWdexf3mjQK2F5DKYFoGNG3JcNkK1TJevTdI/NzJhM63N05I6pCc9bMaD7jsqZlqZc1wbKJ7a/QwLVIO35gig5pL+mgq23q2n4J4A8/Of96h6/eKHjgbVnOT20AqQgeLFxQoQJBAPOwlUMm1ECnGTtZss2X1LAC/pfuyEr/kCy1IU1g6ffAmWu2hBWlxkrsvjXHGwhy/dpjTC6OSolEsaL3HsTztr8CQQDi0NKDn9E/7r2adpDuqlRbED2OawdWOpPY6S0YDnTG415254n/x76rQslnRHIDHqkJUivHjC3k/Ch9B50HoHOxAkBZzU4EFBANz0Y+F90LZJNNVZ0qsiT/dlRUFV+zWy59TW18QyNDsvZy7/FccgYlQ/MGgqc1VNxk33qyumyNWd6TAkEAvA3JTKp4Mpq+B1Bg0BDXCf2IHAmvNpYwuPpzkeuCdNhVHR7R8wlok9Q26nD8WovUOM8xTyxxbNaIt0lVr9ofsQJBAMlOdSv1dRVj5JPgczfgCGLY84V1sGw8cj1KOVX2xlXLB3hvyWgdIDwfgrnuqzDR4rVogPkXp4d56u8TMZCVVOo=";

    public static String sign(String content, String privateKey, String encode) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));

            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);

            //Signature signature = Signature.getInstance(keyf.getAlgorithm());
            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);

            signature.initSign(priKey);
            signature.update(content.getBytes(encode));

            byte[] signed = signature.sign();

            return Base64.encode(signed);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String sign(String content, String privateKey) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            //Signature signature = Signature.getInstance(keyf.getAlgorithm());
            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(content.getBytes());
            byte[] signed = signature.sign();
            return Base64.encode(signed);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * tostring
     * @param content
     * @param sign
     * @param publicKey
     * @param encode
     * @return
     */
    public static boolean doCheck(String content, String sign, String publicKey, String encode) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

            signature.initVerify(pubKey);
            signature.update(content.getBytes(encode));

            boolean bverify = signature.verify(Base64.decode(sign));
            return bverify;

        } catch (Exception e) {
            return false;
        }
    }

    public static boolean doCheck(String content, String sign, String publicKey) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

            signature.initVerify(pubKey);
            signature.update(content.getBytes());

            boolean bverify = signature.verify(Base64.decode(sign));
            return bverify;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public static void genPublicAndPrivateKey() {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();


        String publicKeyString = Base64.encode(publicKey.getEncoded());
        // 得到私钥字符串
        String privateKeyString = Base64.encode(privateKey.getEncoded());

        System.out.print(publicKeyString + "," + privateKeyString);

    }
}
